<template>
  <FIPanel>
    <!-- <el-row>
      <el-form :model="formValue">
        <el-span :span="18">
          <el-form-item label="审核意见" prop="processInstanceId">
            <FIInput :rows="2" type="textarea" />
          </el-form-item>
        </el-span>
      </el-form>
    </el-row> -->
    <el-form :model="form" label-width="auto" style="width: 100%" v-loading="isLoading">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="审核意见"> <el-input v-model="form.comment" type="textarea" :rows="3" /> </el-form-item>
        </el-col>
        <el-col :span="12" v-if="loadData?.ifShowAssignee != 'None'">
          <el-form-item label="选择下一步用户">
            <!-- <el-input v-model="form.aprovalName" /> -->
            <FISelect
              v-model="form.assignee"
              :options="loadData.assignUser"
              :props="{ label: 'userName', value: 'userId' }"
              displayKey="userName"
              multiple
              filterable
              @change="assingneeUserSelect"
            ></FISelect>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="loadData?.ifShowAssignee != 'None'"></el-col>
        <el-col :span="12" v-if="loadData?.ifNotify != 'false'">
          <el-form-item label="选择告知用户">
            <FISelect
              v-model="form.notifyUser"
              :options="loadData.notifyUser"
              :props="{ label: 'userName', value: 'userId' }"
              multiple
              filterable
              @change="notifyUserSelect"
            ></FISelect>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="loadData?.ifNotify != 'false'"></el-col>
        <el-col :span="8">
          <el-form-item label="部门">
            <el-input v-model="loadData.aprovalDeptName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签名">
            <el-input v-model="loadData.aprovalName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核时间">
            <el-input v-model="loadData.aprovalTime" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <div class="BAP-button-group">
          <template v-for="(item, index) in loadData.buttons" :key="item">
            <FIButton
              v-if="item.name"
              type="primary"
              @click="handleBtnClick(item, index)"
              :disabled="index == disabledBtnIndex"
              >{{ item.name }}</FIButton
            >
          </template>
        </div>

        <!-- <el-button type="primary"   @click="onSubmit">同意</el-button>
        <el-button>回退</el-button> -->
      </el-form-item>
    </el-form>
  </FIPanel>
</template>
<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
// import FIForm from '@/components/FIForm.vue'
import FIPanel from '@/components/FIPanel.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import FIButton from '@/components/FIButton.vue'
import { useMessage, useMessageBox } from '@/hooks/message'
const props = defineProps({
  processInstanceId: {
    type: String,
    default: '',
  },
  taskId: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(['submitApprove', 'showNextTip'])
const form = reactive({
  comment: '',
  assignee: '', // 选择下一步用户
  assigneeName: [],
  notifyUser: '', // 选择告知用户
  notifyUserName: [], // 选择告知用户
  aprovalDeptName: '',
  aprovalName: '',
  aprovalTime: '',
})
let loadData: any = ref({})
// 搜索查询函数
const searchFn = () => {
  // 页面搜索数据组装
  const obj = {
    processInstanceId: props.processInstanceId,
    taskId: props.taskId,
  }

  // const apiUrl = proxy.$Button_api('/bpm-service/procInstInfo/queryProVariable', route.name)
  apiRequestPost('/bpm-service/GeneralApprove/initLoad', obj).then((res) => {
    if (res.data.success) {
      loadData.value = res.data.data
      loadData.value.buttons = JSON.parse(res.data.data.buttons)
      //   Array.isArray(loadData.value.buttons) &&
      //     loadData.value.buttons.forEach((item) => {
      //       //   JSON.parse(item)
      //     })
      console.log('loadData----', loadData.value.aprovalDeptName, loadData.value.buttons)
    }
  })
}
const disabledBtnIndex = ref(-1)
const isLoading = ref(false)
const handleBtnClick = (e, index) => {
  console.log('handleBtnClick----', e, index)
  let info: any = {}
  //   info.setByNode('inqu')
  var approvalResult = e.name
  info.approvalResult = approvalResult
  info.transitionKey = e.id
  var transitionName = e.name
  info.transitionName = e.name

  info.processInstanceId = loadData.value.processInstanceId
  info.taskId = loadData.value.taskId
  info.ifNotify = loadData.value.ifNotify
  // info.buttons = loadData.value.buttons
  info.aprovalDeptName = loadData.value.aprovalDeptName
  info.taskDeptEname = loadData.value.taskDeptEname
  info.taskDeptCname = loadData.value.taskDeptCname
  info.aprovalDept = loadData.value.aprovalDept
  info.aprovalId = loadData.value.aprovalId
  info.aprovalName = loadData.value.aprovalName
  info.outTransationSize = loadData.value.outTransationSize
  //   var callBack = {
  //     onSuccess: function (info) {
  //       $('#button > :button').each(function () {
  //         $(this).attr('disabled', 'disabled')
  //       })
  //       window.parent.submitApprove()
  //       window.parent.showNextTip(info.getMsg())
  //     },
  //     onFail: function (msg) {
  //       useMessageBox().confirm(msg)
  //     },
  //   }
  //   var opinionCheck = e.opinionCheck //意见填写校验
  //   var assignUserCheck = e.assignUserCheck //指定用户校验，目前不用
  //   var confirmCheck = e.confirmCheck //提交确认
  //   var bizCheck = e.bizCheck //业务校验
  var bizData = ''
  if (e.bizCheck == 'Y') {
    try {
      var processInstanceId = loadData.value.processInstanceId
      var taskId = loadData.value.tableId
      var rs = window.parent.frames[0].bizCheckMethod(approvalResult, processInstanceId, taskId)
      var result = rs.result //校验结果是否通过
      var message = rs.message //校验不通过提示信息
      var data = rs.data //返回业务数据
      if (!result) {
        if (message != undefined && message != null && message != '') {
          useMessageBox().confirm(message)
        }
        return
      }
      bizData = data
    } catch (error) {
      useMessageBox().confirm('业务校验错误')
      return
    }
    // info.set('V_BIZ_DATA', bizData)
    info.V_BIZ_DATA = bizData
  }
  if (e.opinionCheck == 'Null' && form.comment.trim() != '') {
    useMessageBox().confirm('不能填写审核意见')
    return
  }
  if (e.opinionCheck == 'NotNull' && form.comment.trim() == '') {
    useMessageBox().confirm('请填写审核意见')
    return
  }

  var comment = form.comment
  var addComment = ''
  if (loadData.value.ifShowAssignee != 'None') {
    if (e.assignUserCheck == 'NotNull' && form.assignee.length <= 0) {
      useMessageBox().confirm('请选择下一步用户！')
      return
    }
    // info.set('assignee', $('#inqu_status-0-assignee').data('kendoMultiSelect').value())
    info.assignee = form.assignee
    // info.set(
    //   'assigneeName',
    //   _.map($('#inqu_status-0-assignee').data('kendoMultiSelect').dataItems(), _.iteratee('textField'))
    // )
    info.assigneeName = form.assigneeName
    // addComment +=
    //   '已选择经办人：' +
    //   _.map($('#inqu_status-0-assignee').data('kendoMultiSelect').dataItems(), _.iteratee('textField'))
    addComment += '已选择经办人：' + form.assigneeName //??? 循环经办人
    addComment += '；'
  }
  if (loadData.value.ifNotify == 'true') {
    // info.set('notifyUser', $('#inqu_status-0-notifyUser').data('kendoMultiSelect').value())
    info.notifyUser = form.notifyUser
    // info.set(
    //   'notifyUserName',
    //   _.map($('#inqu_status-0-notifyUser').data('kendoMultiSelect').dataItems(), _.iteratee('textField'))
    // )
    info.notifyUserName = form.notifyUserName // 告知人员
    // addComment +=
    //   '告知人员：' + _.map($('#inqu_status-0-notifyUser').data('kendoMultiSelect').dataItems(), _.iteratee('textField'))
    addComment += '告知人员：' + form.notifyUserName //??? 循环告知人员
  }
  if (addComment.length > 0) {
    comment += '（' + addComment + '）'
  }
  //   info.set('inqu_status-0-comment', comment)
  info['comment'] = comment
  if (e.confirmCheck == 'Y') {
    var cf = confirm('您确认“' + transitionName + '”吗？')
    if (!cf) {
      return
    }
    // useMessageBox()
    //   .confirm('您确认“' + transitionName + '”吗？')
    //   .then((cf) => {
    //     if (!cf) {
    //       return
    //     } else {
    //       //
    //     }
    //   })
  }
  var method = 'submit'
  if (e.id === 'return') {
    method = 'returns'
  } else if (e.id === 'disEndProc') {
    method = 'disEndProc'
  }
  isLoading.value = true
  disabledBtnIndex.value = index
  apiRequestPost('/bpm-service/GeneralApprove/' + method, info)
    .then((res) => {
      isLoading.value = false
      if (res.data.success) {
        // 禁用当前提交按钮---
        emits('submitApprove')
        emits('showNextTip', res.data.message)
        disabledBtnIndex.value = index
      } else {
        disabledBtnIndex.value = -1
      }
    })
    .catch(() => {
      disabledBtnIndex.value = -1
      isLoading.value = false
    })
}
const assingneeUserSelect = (e) => {
  console.log('assingneeUserSelect', e)
  let arr = []
  if (e.length > 0) {
    e.forEach((item) => {
      for (let i = 0; i < loadData.value.assignUser.length; i++) {
        if (item === loadData.value.assignUser[i].userId) {
          arr.push(loadData.value.assignUser[i].userName)
          break
        }
      }
    })
  }
  form.assigneeName = arr
}
const notifyUserSelect = (e) => {
  console.log('notifyUserSelect', e)
  let arr = []
  if (e.length > 0) {
    e.forEach((item) => {
      for (let i = 0; i < loadData.value.notifyUser.length; i++) {
        if (item === loadData.value.notifyUser[i].userId) {
          arr.push(loadData.value.notifyUser[i].userName)
          break
        }
      }
    })
  }
  form.notifyUserName = arr
}
onMounted(() => {
  searchFn()
})
</script>
<style lang="less" scoped>
.BAP-button-group {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
